﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/*
 * Author:Conis
 * Date:
 * Description:分页的结构体及操作
 */

namespace Conis.Squirrel.SqlBuilder
{
    /// <summary>
    /// 分页信息的结构体
    /// </summary>
    public struct Pagination
    {
        /// <summary>
        /// 页索引
        /// </summary>
        public int PageIndex;
        /// <summary>
        /// 每页大小
        /// </summary>
        public int PageSize;
        /// <summary>
        /// 总页数
        /// </summary>
        public int PageCount;
        /// <summary>
        /// 总记录数
        /// </summary>
        public int RecordCount;
        /// <summary>
        /// 当前页总记录数
        /// </summary>
        public int CurrentCount;
    }

    /// <summary>
    /// 对分页的操作，包括计算开始及结束的索引，重新计算页总数等
    /// </summary>
    public class PaginationHelper
    {
        /// <summary>
        /// 重新计算分页，计算页总数、重新获取页索引
        /// </summary>
        public static Pagination EvalPagination(Pagination pagination)
        {
            double pageCount = Convert.ToDouble(pagination.RecordCount) / pagination.PageSize;
            pagination.PageCount = (int)Math.Ceiling(pageCount);

            //PageIndex不能小于等于0
            if (pagination.PageIndex <= 0)
            {
                pagination.PageIndex = 1;
            }

            //PageIndex不能大于PageICount
            if (pagination.PageIndex > pagination.PageCount)
            {
                pagination.PageIndex = pagination.PageCount;
            }
            return pagination;
        }

        /// <summary>
        /// 获取开始索引位置
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static int StartIndex(int pageIndex, int pageSize)
        {
            if (pageIndex <= 1)
            {
                return 1;
            }

            return pageIndex * pageSize - pageSize + 1;
        }

        /// <summary>
        /// 获取结束的索引位置
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static int EndIndex(int startIndex, int pageSize)
        {
            return startIndex + pageSize - 1;
        }
    }
}
